<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use app\common\model\Message;
use app\common\model\Sms;
use app\manage\model\Member;
use app\manage\model\Token;
use buwang\base\MemberBaseController;
use buwang\service\UserService;
use app\common\model\SysLog;
use app\common\model\SysNotice;
use app\common\model\User;
use app\common\model\MemberMiniapp;
use app\common\model\Member as commonMember;
use think\Exception;
use think\facade\Config;
use think\facade\View;
use app\common\model\SysNoticeCategory;

class Index extends MemberBaseController
{
    public function index()
    {
        View::assign('total_message_unread', Message::total(1, $this->uid, 0));
        $this->layout && $this->app->view->engine()->layout($this->layout);
        return view();
    }

    /**
     * 租户首页
     * @return \think\Response
     */
    public function dashboard()
    {
        $member_id = $this->user->top_id;
        $user_total = commonMember::addUserTotal($member_id);//用户数量
        $extract_total = commonMember::extractTotal($member_id);//用户提现
        $recharge_total = commonMember::rechargeTotal($member_id);//用户充值
        $app_total = commonMember::appTotal($member_id);//用户充值
        $base_config_member_notification = bw_config('base.member_notification', '');
        //租户资讯分类
        $cate = SysNoticeCategory::getBaseList();
        $cate = $cate['list'];
        $cate_id = 0;
        if ($cate) $cate_id = $cate[0]['id'];
        if ($this->request->isAjax()) {
            return $this->success('success', compact('base_config_member_notification','user_total', 'extract_total', 'recharge_total', 'app_total', 'cate', 'cate_id'));
        } else {
            return view('', compact('user_total', 'extract_total', 'recharge_total', 'app_total', 'cate', 'cate_id'));
        }
    }

    /**
     * 获取后台菜单初始化数据
     * @param string $miniapp_dir 获取系统菜单可不传,获取应用菜单时传递应用目录名
     * @return \think\response\Json
     */
    public function menu($miniapp_dir = '')
    {
        //获取菜单信息
        list($homeInfo, $logoInfo, $menuInfo) = Member::getMenuList($this->user, $miniapp_dir);
        $systemInit = [
            'homeInfo' => $homeInfo,
            'logoInfo' => $logoInfo,
            'menuInfo' => $menuInfo,
        ];
        return json($systemInit);
    }

    /**
     * 租户登录
     * @return \think\Response|\think\response\Redirect|\think\response\View
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $data = [
                'mobile' => $this->request->param('mobile/s'),
                'password' => $this->request->param('password/s'),
                'captcha' => $this->request->param('captcha', ''),
            ];
            $this->validate($data, 'Manage.member_login');
            //验证密码是否正确
            $admininfo = UserService::validateMember($data['mobile'], $data['password']);
            $admin = $admininfo['rs'];
            if (!$admin) return $this->error($admininfo['error']);

            $rs = UserService::loginMember($admin, true);

            if (!$rs['rs']) return $this->error($rs['error']);
            $rs['rs']['session_id'] = get_session_id();
            event('RequestStart', [$this->request, 'member', '/manage/member.Index/login', $admin, 200, '', 0, false]);
            return $this->success('登录成功', $rs['rs']);
        }
        if ($this->isUserLogin) return $this->redirect('manage/member/index');
        $this->layout && $this->app->view->engine()->layout($this->layout);
        return view();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $member = $this->user;
        $scopes = $this->scopes;
        if ($scopes != 'member') return $this->error('scopes获取错误');
        if ($this->request->isPost()) {
            if (!$this->token) return $this->error('已退出登录，勿重复点击');
            $res = Token::deleteRedisToken($this->token, $member['sub_member_id'] ?: $member['id'], $scopes);
            if (!$res) {
                return $this->error(Token::getError('操作失败'));
            } else {
                return $this->success('退出成功');
            }
        }

    }

    /**
     * 注册租户member
     * @return \think\response\View
     */
    public function add()
    {
        $top_id = 0;
        if ($this->request->isPost()) {
            $param = $this->request->post(['username', 'nickname', 'mobile', 'safe_password', 'password', 'code']);
            $param['username'] = $param['nickname'] = 'bw' . $param['mobile'];
            $param['safe_password'] = '123456';
            if(!Sms::check($param['mobile'], $param['code'], 'register')) return $this->error(Sms::getError());
            $result = Member::createAdmin($param, $top_id, true, true, true);
            //NOTE 需要验证验证码
            if ($result) {
                Sms::clear($param['mobile'], 'register');
                return $this->success('注册成功！');
            } else {
                return $this->error(Member::getError());
            }
        }
        return view('reg');
    }


    /**
     * 得到登录日志
     */
    public function getMemberLoginInfo()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $res = SysLog::getMemberLoginInfo($this->user->top_id, $page, $limit);
        return $this->success('操作成功', $res);
    }

    /**
     * 得到系统公告
     */
    public function getNoticeList()
    {

        $page = $this->request->get('page/d', 1);
        $limit = $this->request->get('limit/d', 10);
        $cate_id = $this->request->get('cate_id/s', 1);
        $res = SysNotice::getNoticeList($page, $limit, ['cate_id' => $cate_id]);
        return $this->success('操作成功', $res);
    }

    /**
     * 得到统计图数据
     */
    public function getEchartsInfo()
    {
        $data_time = [];
        //循环得到前五年的起始时间戳
        for ($x = 5; $x >= 0; $x--) {
            $year = date('Y', strtotime("-{$x} year"));
            $before = date('Y-01-01', strtotime("-{$x} year"));
            $arfer = date('Y-12-31', strtotime("-{$x} year"));
            $data_time[$year] = [
                'before' => $before,
                'arfer' => $arfer
            ];
        }
        //得到租户所有的应用
        $member_id = $this->user->top_id;
        $applist = MemberMiniapp::where('member_id', $member_id)->column('appname', 'id');
        if (!$applist) $applist = [0 => '暂无应用'];
        $member_miniapp_ids = array_keys($applist);//年份
        foreach ($data_time as $k => &$v) {
            $person = [];
            //统计租户每个应用下的用户数量
            $order_list = User::where('create_time', 'between time', [$v['before'], $v['arfer']])
                ->where('member_miniapp_id', 'in', $member_miniapp_ids)
                ->group("member_miniapp_id")
                ->order('create_time asc')
                ->column('member_miniapp_id,count(*) as count', 'member_miniapp_id');
            foreach ($applist as $k => $val) {
                if (isset($order_list[$k])) {
                    $person[$k] = $order_list[$k]['count'];
                } else {
                    $person[$k] = 0;
                }
            }

            $v['data'] = $person;
            //$v['data'] = $order_list;
        }
        //组装数据
        $years = array_keys($data_time);//年份
        array_unshift($years, 'product');

        $datas = [];//应用用户数据

        foreach ($data_time as $kk => $vv) {
            foreach ($applist as $ks => $vals) {
                if (!isset($datas[$ks])) $datas[$ks][] = $vals;
                $datas[$ks][] = $vv['data'][$ks];
            }
        }
        $datas = array_values($datas);
        array_unshift($datas, $years);

        $res = [
            'data' => $datas,
            'count' => count($applist),
            'year' => $years,
        ];
        return $this->success('操作成功', $res);
    }

    /**
     * 获取站内信
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function messageList()
    {
        if (request()->isAjax()) {
            $page = $this->request->get('page', 1);
            $limit = $this->request->get('limit', 10);
            $all = $this->request->get('all/d', 0); //全部未读
            if (!$all) {
                $list = Message::list(1, $this->uid, $page, $limit);
            } else {
                $list = Message::list(1, $this->uid, 0, 0, 0);
            }
            return $this->success('获取成功', compact('list'));
        }
        $this->layout && $this->app->view->engine()->layout($this->layout);
        View::assign('total', Message::total(1, $this->uid));
        return view();
    }

    public function messageRead($id)
    {
        if (request()->isGet()) {
            try {
                Message::read($id);
                return $this->success('操作成功');
            } catch (Exception $e) {
                return $this->error($e->getMessage());
            }

        }
    }

    /**
     * 找回密码
     */
    public function forget()
    {
        if ($this->request->isPost()) {
            $data = [
                'mobile' => $this->request->param('mobile/s'),
                'password' => $this->request->param('password/s'),
                'password_confirm' => $this->request->param('password_confirm/s'),
                'code' => $this->request->param('code/s'),
            ];
            $this->validate($data, 'Manage.member_forget');
            //验证手机号是否已注册
            $admininfo = Member::memberExist($data['mobile']);
            if ($admininfo == 0)
                return $this->error('该手机号还未注册，请前往注册');
            //验证短信验证码是否正确
            if (!Sms::check($data['mobile'], $data['code'], 'forget')) return $this->error(Sms::getError());
            $param = [
                'password' => $data['password'],
                'password2' => $data['password_confirm'],
                'id' => $admininfo,
            ];
            $result = Member::updatePassword($param, true);
            if ($result) {
                //如果变更了操作密码
                if (isset($result['password']) && $result['password']) {
                    //Sms::clear($param['mobile'],'forget');
                }
                return $this->success('操作成功', $result);
            } else {
                return $this->error(Member::getError());
            }
        }
        return view('forget');
    }
}
